// model文件夹就是这个路由的dva的模块

// 这四个都是ts数据类型
import { Effect, Reducer, Subscription } from 'umi';
import { todolistApi } from '@/utils/api';

export interface IndexModelState {
  name: string;
  list: string[];
}

export interface IndexModelType {
  // 对于一个确定，且不会变的字符串，可以直接将这个值作为这个字符串的类型
  namespace: 'index';
  state: IndexModelState;
  effects: {
    query: Effect;
    getList: Effect;
  };
  reducers: {
    save: Reducer;
    add: Reducer;
    remove: Reducer;
    load: Reducer;
  };
  subscriptions: { setup: Subscription };
}

const IndexModel: IndexModelType = {
  // 命名空间
  namespace: 'index',

  // 仓库数据
  state: {
    name: '',
    list: [],
  },

  // 写异步方法的
  // 这个一个generator函数，dva基于saga的
  effects: {
    *query({ payload }, { call, put }) {},
    // 异步获取list
    *getList({ payload }, { call, put }) {
      const res = yield call(todolistApi);
      yield put({
        type: 'load',
        payload: res.result,
      });
    },
  },

  // 写同步方法的
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    add(state, action) {
      return {
        ...state,
        list: [...state.list, action.payload],
      };
    },
    remove(state, action) {
      return {
        ...state,
        list: state.list.filter((item: string) => item !== action.payload),
      };
    },
    load(state, action) {
      return {
        ...state,
        list: action.payload,
      };
    },
  },
  subscriptions: {
    // 会自动执行，里面可以去监听url
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/todolist') {
          dispatch({
            type: 'getList',
          });
        }
      });
    },
  },
};

export default IndexModel;
